﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using OpenTK;
using System.Windows.Forms;

namespace NLE
{
    public class Camera
    {

        #region Singleton

        private static Camera instance;

        private Camera()
        {
            Zoom = 1.0f;
        }

        public static Camera Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Camera();
                }
                return instance;
            }
        }

        #endregion

        public Matrix4 Transformation { get; private set; }        

        public Matrix4 Projection
        {
            get { return Matrix4.CreateOrthographic(((float)Control.Width / Zoom), ((float)Control.Height / Zoom), 0, 1); }
            set { Projection = value; }
        }

        public Matrix4 View { get { return Matrix4.CreateTranslation(Position.InvertX()); } set { View = value; } }

        public Vector3 Position { get; set; }

        public float Zoom { get; set; }

        public Control Control { get; set; }

        public void Tick(float dTime)
        {
            // Clamp the zoom

            Zoom = (float)Math.Round((double)Zoom, Zoom < 0.5f ? 2 : 1, MidpointRounding.AwayFromZero);


            Zoom = Math.Max(0.1f, Zoom);
            Zoom = Math.Min(10.0f, Zoom);

            Transformation =       // Thanks to o KB o for this solution
  Matrix4.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0)) *
                             Matrix4.CreateRotationZ(0.0f) *
                             Matrix4.Scale(Zoom, Zoom, 0) *
                             Matrix4.CreateTranslation(new Vector3(Control.Width * 0.5f, Control.Height * 0.5f, 0));

        }
    }
}
